import axios from 'axios'
import config from '@/api/config'
import { MessageBox, Message, } from 'element-ui'
import store from '@/store'
import { getToken, getRefreshToken, setToken } from '@/utils/auth'
import router from '@/router'
import system from '@/api/apiSystem'
import { setTimeout } from 'core-js'
// create an axios instance
const service = axios.create({
  baseURL: "http://localhost:", // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 15 * 1000 // request timeout
})
function onceRecently(fn) {
  let can, result
  if (Object.prototype.toString.call(fn) !== "[object Function]") throw new Error('请传递一个函数');
  return function (...rest) {
    if (can) return result
    can = true;
    setTimeout(() => { can = false }, 3000)
    result = fn.apply(this, rest);
    return result
  };
};
var toLogin = (msg) => {
  logout()
  // MessageBox.alert('是否转到登录页？', msg, {
  //   confirmButtonText: '确定',
  //   callback: action => {
  //     if (action === 'confirm') {
  //       logout()
  //     }
  //   }
  // });
}
function logout(){
  localStorage.clear()
  store.dispatch('permission/generateRoutes')
  router.push(`/login?redirect=${router.app.$route.fullPath}`)
}
let onceToLogin = onceRecently(toLogin)
// request interceptor
service.interceptors.request.use(
  config => {
    if (/^\d+/.test(config.url)) {
      var port = /^\d+/.exec(config.url)
      config.baseURL = config.baseURL + port
      config.url = config.url.replace(port, '')

    }
    // do something before request is sent
    // debugger
    config.headers['Authorization'] = getToken()
    return config
  },
  error => {
    // do something with request error
    console.log('request', error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    //  debugger
    if (res.code == 400) {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 3 * 1000
      })
      return Promise.reject(new Error(res.msg || 'Error'))
    }
    return res
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 20000) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }

  },
  error => {
    console.log('error', error)
    if (error && error.response) {
      var response = error.response
      var httpStatusCode = response.status
      if (httpStatusCode == 401) {
        if (response.data.code == 4012) {//登录token已过期,可刷新token
          system.post('manager/RefreshToken', { RefreshToken: getRefreshToken() })
            .then((res) => {
              setToken(res.accessToken)
            })
            .catch(() => { })
        } else {
          onceToLogin(response.data.msg)
        }
      } else {
        Message({
          message: response.data.msg??'服务异常',
          type: 'error',
          duration: 5 * 1000
        })
      }
    } else {
      if(error.toString().indexOf('timeout')>-1){
        Message({
          message: '请求超时',
          type: 'error',
          duration: 3 * 1000
        })
      }else{
        Message({
          message: error,
          type: 'error',
          duration: 3 * 1000
        })
      }
      
    }
    return Promise.reject(error)
  }
)



export default service
